<script>
export default {
  name: 'Button',
  inheritAttrs: false,
  props: {
    enter: {
      type: Boolean,
      default: false
    },
    isText: {
      type: Boolean,
      default: false
    },
    remove: {
      type: Boolean,
      default: false
    },
    close: {
      type: Boolean,
      default: false
    },
    isDebounce: {
      type: Boolean,
      default: true
    },
    delay: {
      type: Number,
      default: 200
    }
  },
  data() {
    return {
      loading: false,
      debounceDlickHandle: () => {},
      enterFlag: false
    }
  },
  activated() {
    this.addEnter()
  },
  deactivated() {
    this.removeEnter()
  },
  created() {
    this.addEnter()
    this.genDebounceHandle()
  },
  beforeDestroy() {
    this.removeEnter()
  },
  methods: {
    genDebounceHandle() {
      if (this.isDebounce) {
        this.debounceDlickHandle = this.$debounce(this.clickHandle, this, this.delay)
      } else {
        this.debounceDlickHandle = this.clickHandle
      }
    },
    clickHandle() {
      const { click } = this.$listeners
      if (this.$attrs.loading !== undefined) {
        this.$emit('click')
        return
      }
      this.loadingHandle(click)
    },
    // loading
    async loadingHandle(fn) {
      this.loading = true
      try {
        const result = await fn()
        if (result instanceof Promise) {
          result.then(() => {
            if (this.close) {
              this.$closePage()
            }
          }).finally(() => {
            this.loading = false
          })
        } else {
          this.loading = false
        }
      } catch (e) {
        this.loading = false
      }
    },
    // enter
    pressEnter(e) {
      if (e.keyCode === 13) {
        // this.$emit('click')
        this.debounceDlickHandle()
      }
    },
    // addEnter
    addEnter() {
      if (this.enter && !this.enterFlag) {
        this.enterFlag = true
        window.addEventListener('keydown', this.pressEnter)
      }
    },
    // removeEnter
    removeEnter() {
      if (this.enter) {
        window.removeEventListener('keydown', this.pressEnter)
        this.enterFlag = false
      }
    }
  },
  render(h) {
    const cnf = {
      class: ['btn', { btnText: this.isText, remove: this.remove }],
      props: {
        size: 'mini',
        ...this.$attrs
      },
      attrs: {},
      on: {
        click: this.debounceDlickHandle
      }
    }
    if (this.$attrs.flag) {
      cnf.attrs.flag = this.$attrs.flag
    }
    if (this.$attrs.loading === undefined) {
      cnf.props.loading = this.loading
    }
    return h('el-button', cnf, this.$scopedSlots.default ? this.$scopedSlots.default() : '')
  }
}
</script>
<style lang="scss" scoped>
    @import "@/styles/btn.scss";
    .btn[class*="el-button--primary"]{
        @include colorBtn(#16BC83);
        color: white !important;
    }
    .btnText{
      padding: 0 !important;
    }
    .remove{
      color: #ff6d6d !important;
    }
</style>
